package team.se.tms.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;

/**
 * 验证码工具类
 *
 * @author winkyle
 * @date 2018/11/14
 */
@Slf4j
public class VerificationCodeUtil {


    /**
     * 将验证码图片写入输出流，并返回验证码字符串
     *
     * @param output 输出流
     * @return 验证码字符串
     * @throws Exception 异常
     * @create on 2018/11/15 by winkyle
     */
    public static String drawImg(ByteArrayOutputStream output) throws Exception {
        // 取随机产生的认证码
        String code = RandomUtil.generateRandomChar(4);
        int width = 112;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics2D g = image.createGraphics();
        // 设定背景色
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        //画边框
        g.setColor(Color.black);
        g.drawRect(0,0,width-1,height-1);
        //将认证码显示到图像中,如果要生成更多位的认证码,增加drawString语句
        g.setColor(Color.black);
        Font font = new Font("华文隶书",Font.BOLD,38);
        g.setFont(font);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double fontX = (width - bounds.getWidth()) / 2;
        double fontY = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = fontY - ascent;
        g.drawString(code, (int)fontX, (int)baseY);
        // 随机产生10个干扰点
        Random rand = new Random();
        for (int i=0;i<10;i++) {
            int x = rand.nextInt(width);
            int y = rand.nextInt(height);
            g.drawOval(x,y,1,1);
        }
        // 释放图形上下文
        g.dispose();
        // 输出图像到页面
        ImageIO.write(image, "JPEG", output);
        log.debug("生成的验证码是{}",code);
        return code;
    }

}
